package resultbase

import (
	"bufio"
	"fmt"
	"os"
	"sync"
)

/**
  @author: weicai
  @since: 2024/4/23
  @desc: 结果处理器
**/

type WtesterResults struct {
	Name         string  // 名称
	ResponseTime float64 // 响应时间
	RequestsType string  // 请求类型
	Exception    string  // 异常
	Concurrences uint8   // 并发
}

func (w *WtesterResults) toByte() float64 {
	return w.ResponseTime
}

func writeResults(results *chan []byte) {
	file, _ := os.OpenFile("result.txt", os.O_CREATE|os.O_WRONLY, 0644)
	scannerW := bufio.NewWriter(file)
	for r := range *results {
		_, err := scannerW.Write(r)
		if err != nil {
			fmt.Println(err)
			fmt.Println(string(r))
			continue
		}
		_ = scannerW.Flush()
	}
}

func dealTaskResults(results *chan *WtesterResults, resultByte *chan []byte) {
	for r := range *results {
		*resultByte <- []byte(fmt.Sprintf("%s,%f,%d\n", r.Name, r.ResponseTime, r.Concurrences))
	}
}

func DealResults(results *chan *WtesterResults) {
	taskResultMap := make(map[string]chan *WtesterResults)
	resultByte := make(chan []byte, 100)
	var group sync.WaitGroup
	group.Add(1)
	go func() {
		defer group.Done()
		writeResults(&resultByte)
	}()
	for r := range *results {
		if t, ok := taskResultMap[r.Name]; ok {
			t <- r
		} else {
			t = make(chan *WtesterResults, 100)
			taskResultMap[r.Name] = t
			taskResultMap[r.Name] <- r
			group.Add(1)
			go func() {
				defer group.Done()
				dealTaskResults(&t, &resultByte)
			}()
		}
	}
}
